﻿using Aker.Cikislar;
using Aker.DevTeam;
using Aker.Sistem;
using Cikislar;
using DevExpress.XtraBars;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraReports.UI;
using Extensions;
using System;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace Aker
{
    public partial class ArtikelStokVeCikis : XForm
    {
        string[] editAbleColumns;

        public ArtikelStokVeCikis()
        {
            InitializeComponent();
        }

        int[] selectedProducts = null;
        public ArtikelStokVeCikis(int[] selectedProducts)
        {
            InitializeComponent();
            this.selectedProducts = selectedProducts;
        }
        private void Shelf_Load(object sender, EventArgs e)
        {
            gc.Enabled = false;
            if (Environment.MachineName != "KGULCAN")
                btnDeveloper.Visibility = BarItemVisibility.Never;

            if (Data.IsLookupInitialized)
                Data_LookupInitialized();
            else
                Data.LookupInitialized += Data_LookupInitialized;
        }

        void Data_LookupInitialized()
        {
            editAbleColumns = new string[] { "CikilacakKG", "CikilacakMetre", "ShelfId", "Qty" };

            Data.TAM.ShelfTableAdapter.Fill(Data.DB.Shelf);
            Data.TAM.RollTableAdapter.Fill(Data.DB.Roll);

            BindData();

            GridMenu gm = GridManager.GetManager(gv).GridMenu;
            gm.AddMenu("Seçili topları yazdır", Print);

            if (selectedProducts != null)
                gv.ActiveFilterString = "ProductId in (" + string.Join(",", selectedProducts) + ")";

            gv.OptionsView.ShowViewCaption = false;

            this.BarcodeRead += Stock_BarcodeRead;


            gv.CellValueChanged += gv_CellValueChanged;
            gv.RowCellStyle += gv_RowCellStyle;

            gc.Enabled = true;
        }

        private void Print(object sender, EventArgs e)
        {
            int[] rhs = gv.GetSelectedRows();
            if (rhs.Length > 0)
            {
                ProductReportSettings settings = new ProductReportSettings();
                settings.copyCount.Enabled = false;
                if (settings.ShowDialog() == DialogResult.OK)
                {
                    int emptyCount = settings.emptyCount.Value.ToIntNN();

                    DataSet ds = new DataSet();
                    DataTable dt = Data.DB.Product.Clone();
                    dt.Columns.Add("RollId", typeof(int));

                    dt.TableName = "Table";
                    ds.Tables.Add(dt);
                    dt.Columns.Add("Sira", typeof(int));
                    dt.PrimaryKey = null;

                    foreach (int rh in rhs)
                    {
                        DataRow drCurrent = gv.GetDataRow(rh);
                        int rollId = drCurrent["RollId"].ToIntNN();
                        int productId = drCurrent["ProductId"].ToIntNN();

                        DataRow drProduct = Data.DB.Product.FindByProductId(productId);
                        dt.ImportRow(drProduct);

                        DataRow drArticleRoll = dt.NewRow();
                        //drArticleRoll["Sira"] = drArticle["Sira"];
                        drArticleRoll["RollId"] = rollId;
                        dt.Rows.Add(drArticleRoll);
                    }
                    ProductReport pr = new ProductReport(ds, emptyCount, 1);
                    pr.ShowPreview();
                }
            }
        }

        void gv_CellValueChanged(object sender, CellValueChangedEventArgs e)
        {
            if (e.Column.FieldName == "ShelfId" || e.Column.FieldName == "Qty")
            {
                gv.EndEditing();
                DataRow dr = gv.GetDataRow(e.RowHandle);
                int rollId = dr["RollId"].ToIntNN();

                int shelfId = dr["ShelfId"].ToIntNN();
                decimal qty = dr["Qty"].ToDecimalNN();

                AkerDB.RollRow rollRow = Data.DB.Roll.FindByRollId(rollId);

                Data.DM.ExecuteNonQuery("UpdRoll", rollId, shelfId, qty);
            }
        }

        DataTable dt;
        private void BindData()
        {
            dt = Data.DM.ExecuteDataTable("GetRollStock");
            dt.Columns.Add("CikilacakKG", typeof(decimal));
            dt.Columns.Add("CikilacakMetre", typeof(decimal));

            gv.Init(dt);

            gv.SetCaptions("ProductId:Id", "RollId:TopNo", "Qty:Metre", "ShelfId:Raf", "ShelfId:Raf", "CikilacakKG:Çıkılacak KG", "CikilacakMetre:Çıkılacak Metre");
            gv.FormatAsNumber("Qty", "KG", "CikilacakKG", "CikilacakMetre");

            gv.AddSummary("Qty");
            gv.Columns["ShelfId"].ColumnEdit = Utility.GetGLESablon(Data.DB.Shelf, "Name", "ShelfId");

            gv.BestFitColumns();


            if (AppSession.UserInfo.YetkiId == 2 || AppSession.UserInfo.YetkiId == 5)
                gv.MakeReadOnly(editAbleColumns);
            else
                gv.MakeReadOnly();
        }

        void gv_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            if (e.RowHandle > -1 && editAbleColumns.Contains(e.Column.FieldName))
                e.Appearance.BackColor = Color.LightYellow;
        }

        void Stock_BarcodeRead(int Barcode)
        {
            Barkod barkod = new Barkod(Barcode);

            switch (barkod.Tip)
            {
                case Barkod.BarkodTip.Artikel:
                    gv.ActiveFilterString = "ProductId=" + Barcode;
                    break;
                case Barkod.BarkodTip.Raf:
                    gv.ActiveFilterString = "ShelfId=" + Barcode;
                    break;
                case Barkod.BarkodTip.Top:
                    gv.ActiveFilterString = "RollId=" + Barcode;
                    break;
            }
        }

        private void btnDeveloper_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //1000001
            //2000052
            // Stock_BarcodeRead(1000001);
            Stock_BarcodeRead(2000052);
            //Stock_BarcodeRead(8000002);
        }

        private void btnSepeteEkle_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (Kontrol())
            {
                DataTable changes = dt.GetChanges();
                foreach (DataRow dr in changes.Rows)
                {
                    if (dr["CikilacakKG"].ToDecimalNN() > 0 || dr["CikilacakMetre"].ToDecimalNN() > 0)
                    {
                        AkerDB.CikisLinesRow cikisLines = CikisSepet.YeniCikisLines();

                        cikisLines.RollId = dr["RollId"].ToIntNN();
                        //cikisLines.CikilanKG = dr["CikilacakKG"].ToDecimalNN();
                        //Toplarda çıkış KG ya da MT olacak mı olmayacak mı net değiller. Bu yüzden şimdilik metre olarak çıkılıyor.
                        cikisLines.CikilanMetre = dr["CikilacakMetre"].ToDecimalNN();
                        cikisLines.CikilanKG = dr["CikilacakKG"].ToDecimalNN();
                        cikisLines.CikilanAdet = 1;
                        //cikisLines["ProductId"] = dr["ProductId"].ToIntNN();
                        cikisLines["Artikel"] = dr["Artikel"];
                        cikisLines["Desen"] = dr["Desen"];
                        cikisLines["Karışım"] = dr["Karışım"];
                        cikisLines["Ağırlık"] = dr["Ağırlık"];

                        CikisSepet.SepeteAt(cikisLines);
                    }
                }

                btnTemizle.PerformClick();
                ShowInfo("Sepete atıldı.");
            }
        }
        private bool Kontrol()
        {
            gv.EndEditing();

            DataTable changes = dt.GetChanges();
            if (changes != null && changes.Rows.Count > 0)
                return true;
            else
            {
                ShowInfo("Değişiklik yok.");
                return false;
            }
        }

        private void btnSepeteGit_ItemClick(object sender, ItemClickEventArgs e)
        {
            AppSession.MainForm.ShowMdiChildForm(typeof(Cikislar.CikisSepet));
        }

        private void btnTemizle_ItemClick(object sender, ItemClickEventArgs e)
        {
            gv.EndEditing();
            foreach (DataRow dr in dt.Select("isnull(CikilacakKG,0) > 0"))
                dr["CikilacakKG"] = DBNull.Value;

            foreach (DataRow dr in dt.Select("isnull(CikilacakMetre,0) > 0"))
                dr["CikilacakMetre"] = DBNull.Value;
            dt.AcceptChanges();
            //BindData();
            //gv.EndEditing();
            //foreach (DataRow dr in dt.Select("isnull(CikilacakKG,0) > 0 or isnull(CikilacakAdet,0) > 0"))
            //{
            //    dr["CikilacakKG"] = DBNull.Value;
            //    dr["CikilacakAdet"] = DBNull.Value;
            //    dt.AcceptChanges();
            //}
        }

        private void btnCik_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (Kontrol())
            {
                Cikis.TamponuTemizle();
                DataTable changes = dt.GetChanges();
                foreach (DataRow dr in changes.Rows)
                {
                    AkerDB.CikisLinesRow cikisLines = Cikis.YeniTamponSatiri();

                    cikisLines.RollId = dr["RollId"].ToIntNN();
                    cikisLines.CikilanMetre = dr["CikilacakMetre"].ToDecimalNN();
                    cikisLines.CikilanKG = dr["CikilacakKG"].ToDecimalNN();

                    Cikis.TamponaEkle(cikisLines);
                }

                if (Cikis.TamponuCik(1) == System.Windows.Forms.DialogResult.OK)
                {
                    BindData();
                    ShowInfo("Çıkış başarıyla gerçekleştirildi.");
                }
            }
        }

        private void btnYenile_ItemClick(object sender, ItemClickEventArgs e)
        {
            BindData();
        }

        private void btnPidion_ItemClick(object sender, ItemClickEventArgs e)
        {
            string filter = gv.ActiveFilterString;
            AppSession.MainForm.ArtikelRafla();
            btnYenile.PerformClick();
            gv.ActiveFilterString = filter;
        }
    }
}